package com.stylefeng.guns.spider.controller;

import com.stylefeng.guns.spider.io.Line;
import com.stylefeng.guns.spider.io.RandomAccessFileReader;
import com.stylefeng.guns.spider.log.LogView;
import com.stylefeng.guns.spider.model.JsonBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

/**
 * 爬虫Controller
 * @author Administrator
 *
 */
@RestController
public class SpiderFlowController {
	
	@Value("${log.path}")
	private String logFile;

	@Autowired
	private LogView logView;
	

	private static Logger logger = LoggerFactory.getLogger(SpiderFlowController.class);

	@RequestMapping("/userInfo/spider/log")
	public JsonBean<List<Line>> log(String id, String taskId, String keywords, Long index, Integer count, Boolean reversed, Boolean matchcase, Boolean regx) {

		final File tmpLogFile = new File(logFile);

		try (RandomAccessFileReader reader = new RandomAccessFileReader(new RandomAccessFile(logFile,"r"), index == null ? -1 : index, reversed == null || reversed)){
			return new JsonBean<>(reader.readLine(count == null ? 10 : count,keywords,matchcase != null && matchcase,regx != null && regx));
		} catch(FileNotFoundException e){
			return new JsonBean<>(0,"日志文件不存在");
		} catch (IOException e) {
			logger.error("读取日志文件出错",e);
			return new JsonBean<>(-1,"读取日志文件出错");
		}
//		try {
//			logView.realtimeShowLog(tmpLogFile);
//		}catch(FileNotFoundException e){
//			return new JsonBean<>(0,"日志文件不存在");
//		} catch (IOException e) {
//			logger.error("读取日志文件出错",e);
//			return new JsonBean<>(-1,"读取日志文件出错");
//		}
//		return new JsonBean<>(-2,"error");
//		try (RandomAccessFileReader reader = new RandomAccessFileReader(new RandomAccessFile(logFile,"r"), index == null ? -1 : index, reversed == null || reversed)){
//			return new JsonBean<>(reader.readLine(count == null ? 10 : count,keywords,matchcase != null && matchcase,regx != null && regx));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
}
